package uutalk.netcloud.talk.app.ui.Activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.app.ui.MainActivity;
import uutalk.netcloud.talk.app.ui.MainActivityBak;
import uutalk.netcloud.talk.base.android.BaseActivity;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.MqttConstant;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MQTTActionEvent;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.Md5Utils;
import uutalk.netcloud.talk.base.util.PermissionUtils;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.base.util.view.ViewUtil;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.LoginInfo;
import uutalk.netcloud.talk.model.bean.UserInfo;

/**
 * 类描述：
 * 作者：Pengmutian
 * 时间：2018/5/11
 */
public class LoginActivity extends BaseActivity {

    private final int REQUEST_CODE = 999;

    @BindView(R.id.accountET)
    EditText accountET;
    @BindView(R.id.passET)
    EditText passET;

    String userType = "1";
    boolean clickLogin = false;
    private String imei;

    @Override
    public void init() {
        if (Build.VERSION.SDK_INT < 23) {
            TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
            imei = TelephonyMgr.getDeviceId();
            accountET.setText(imei);
        } else {
            if(ActivityCompat.checkSelfPermission(mActivity, PermissionUtils.PERMISSION_READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
                PermissionUtils.requestPermission(mActivity, REQUEST_CODE, PermissionUtils.PERMISSION_READ_PHONE_STATE);
            } else {
                TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                imei = TelephonyMgr.getDeviceId();
                accountET.setText(imei);
            }
        }


    }

    @Override
    public int layoutId() {
        return R.layout.activity_login_hand;
    }

    @Override
    public boolean autoBindEvent() {
        return true;
    }

    @OnClick(R.id.loginBtn)
    public void onLoginClick() {
        if (checkInput()) {
            startLogin();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @android.support.annotation.NonNull String[] permissions, @android.support.annotation.NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_CODE){
             if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                imei = TelephonyMgr.getDeviceId();
                accountET.setText(imei);
                 LogUtils.e("imei >>"+imei);
             }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttActionEvent(MQTTActionEvent event) {
        if (event.getStatus() == MqttConstant.MQTTStatusConstant.CONNECT_FAIL || event.getStatus() == MqttConstant.MQTTStatusConstant.CONNECTION_LOST) {
            progressHudUtil.dismissProgressHud();
            clickLogin = false;
            ToastUtil.makeToast(event.getMessage());
        } else if (event.getStatus() == MqttConstant.MQTTStatusConstant.SUBSCRIBE_FAIL || event.getStatus() == MqttConstant.MQTTStatusConstant.PUBLISH_FAIL) {
            progressHudUtil.dismissProgressHud();
            ToastUtil.makeToast(LanguageUtil.getStringById(R.string.request_error));
            clickLogin = false;
        } else if (event.getStatus() == MqttConstant.MQTTStatusConstant.SUBSCRIBE_SUCCESS) {
            progressHudUtil.dismissProgressHud();
            if (clickLogin) {
                requestLogin();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMessageEvent(MqttMessageEvent event) {
        LogUtils.e(TAG, "onMqttMessageEvent" + event.getMessage().toString());
        if (CMDConstant.UEER_LOGIN_RESP_CMD.equals(event.getMessage().getCmd())) {
            progressHudUtil.dismissProgressHud();
            UserInfo userInfo = JSON.parseObject(event.getMessage().toString(), UserInfo.class);

            if (userInfo.isOk()) {
                UserManager.getInstance().saveUserInfoToLocal(userInfo);
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.setUserType(userType);
                loginInfo.setDeviceId(ViewUtil.getText(true, accountET));
                loginInfo.setDevicePassword(ViewUtil.getText(true, passET));
                UserManager.getInstance().saveLoginInfoToLocal(loginInfo);
                Intent intent = new Intent(mActivity, MainActivity.class);
                startActivity(intent);
            } else if ("6".equals(userInfo.getError_no())) {
                //首次登录
                //startActivity(SetUserInfoActivityAutoBundle.builder(ViewUtil.getText(true, accountET), ViewUtil.getText(true, passET),userType,userInfo.getUser_id()).build(mActivity));
            } else {
                ToastUtil.makeToast(userInfo.getError_msg());
                MQTTManager.getInstance().destory();
            }
        }
    }



    /**
     * 开始登录并获取数据
     */
    private void startLogin() {
        clickLogin = true;
        if (!MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud();
            MQTTManager.getInstance().connect(ViewUtil.getText(true, accountET));
        } else if (MQTTManager.getInstance().isSubscribeSuccess()) {
            requestLogin();
        } else {
            ToastUtil.makeToast(LanguageUtil.getStringById(R.string.get_data_erro));
        }
    }

    /**
     * 请求用户信息
     */
    private void requestLogin() {
        progressHudUtil.showProgressHud();
        Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createLoginBean(userType, ViewUtil.getText(true, accountET), Md5Utils.md5(ViewUtil.getText(true, passET))));
        MQTTManager.getInstance().publish(publication);
    }


    private boolean checkInput() {
        if (ViewUtil.isEmpty(accountET)) {
            ToastUtil.makeToast("请输入序列号");
            return false;
        }
        if (ViewUtil.isEmpty(passET)) {
            ToastUtil.makeToast("请输入密码");
            return false;
        }
        return true;
    }

    @Override
    public void finish() {
        if (!UserManager.getInstance().isHasLogin()) {
            MQTTManager.getInstance().destory();
        }
        super.finish();
    }
}
